import React, { Fragment, PureComponent } from 'react';

import TodoListUl from './TodoListUl'

class TodoList extends PureComponent {
  state = {
    keywords: '',
    list: []
  }

  handleChange = (e) => {
    this.setState({
      keywords: e.target.value
    })
  }

  handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      // this.state.list.push({
      //   name: this.state.keywords,
      //   isFinished: false
      // })
      // this.setState({
      //   keywords: ''
      // })
      this.setState({
        keywords: '',
        list: [
          ...this.state.list,
          {
            name: this.state.keywords,
            isFinished: false
          }
        ]
      })
    }
  }

  handleClick = (index) => {
    return (e) => {
      this.state.list.splice(index, 1)
      this.setState({})
    }
  }

  handleCheckboxClick = (isFinished, i) => {    
    return () => {
      if (!isFinished) {
        this.state.list.splice(i, 1, {
          name: this.state.list[i].name,
          isFinished: true
        })
        this.setState({})
      } else {
        this.state.list.splice(i, 1, {
          name: this.state.list[i].name,
          isFinished: false
        })
        this.setState({})
      }
    }
  }

  render() {
    return (
      <>
        <div>
          <input 
            type="text" 
            value={this.state.keywords}
            onChange={this.handleChange}
            onKeyUp={this.handleKeyUp}
          />
        </div>
        <div>未完成：</div>
        <TodoListUl
          list={this.state.list}
          handleCheckboxClick={this.handleCheckboxClick}
          handleClick={this.handleClick}
          finished={false}
        ></TodoListUl>
        <div>已完成：</div>
        <TodoListUl
          list={this.state.list}
          handleCheckboxClick={this.handleCheckboxClick}
          handleClick={this.handleClick}
          finished={true}
        ></TodoListUl>
      </>
    );
  }
}

export default TodoList;